# -*- coding: utf-8 -*-

'''
Created on 18.07.2011

@author: Vlasov A. I. <root@proscript.ru>
'''
import datetime, calendar

from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.http import HttpResponseRedirect, Http404

from settings import OKNO
 
from okno.forms import SearchForm
from okno.models import Statement, Citizen

from util.template import render_by_request_context

#TODO: Добавить возможность вводить паспортыне данные прямо из портала
@login_required
def citizen(request, id):
    if request.method == 'GET':
        try:
            citizen = Citizen.objects.get(id=id)
        except:
            return HttpResponseRedirect(u'/okno/search/')
        
        request.session.update({ 'citizen': int(id),
                                'type': 'statement', })
        
        old_statements = Statement.objects.filter(asp_citizen=citizen)
        
        return render_by_request_context(request, 'okno/citizen.html', {
                                                    'citizen': citizen,
                                                    'old_statements': old_statements, })
    
    return HttpResponseRedirect(u'/okno/search/')

@login_required
def view (request, id, _print=False):
    try:
        statement = Statement.objects.get(id=id)
    except Exception:
        raise Http404(u'Заявления с таким номером (%s) нет в базе'%id)

    if _print:
        return render_by_request_context(request, 'okno/statement_print.html', {'st': statement })
    
            
    return render_by_request_context(request, 'okno/statement_view.html', {'st': statement })

#TODO: сделать интерфейс поиска удаленных ПКУ
@login_required
def journal(request, page=1, year=None, month=None, day=None, prnt=None):
    
    if not page or page < 1:
        page = 1
    
    
    try:
        _date = datetime.date(int(year), int(month), int(day))
    # TypeError - дата не указана
    # ValueError - дала не верна

        statement_list = Statement.objects.filter(date=_date)
        year = _date.year
    except Exception:
        if not year or year < 2011:
            year = datetime.date.today().year
        _date = datetime.date(int(year), datetime.date.today().month, datetime.date.today().day)
    
        statement_list = Statement.objects.filter(
            date__gte=datetime.date(int(year), 1, 1)).filter(
            date__lte=datetime.date(int(year), 12, 31)).order_by('number')

    paginator = Paginator(statement_list, OKNO['st_per_page'])
    
    try:
        statements = paginator.page(page)
    except PageNotAnInteger:
        statements = paginator.page(1)
    except EmptyPage:
        statements = paginator.page(paginator.num_pages)
    
    from util import print_odf
    import os
    if prnt:
        return print_odf(request, '/var/calculate/www/dj/okno/templates/okno/doc/journal.odt', {'page': statement_list, 'year': year })

    return render_by_request_context(request, 'okno/statement_journal.html', {'page': statements, 'date': _date })

@login_required
def search(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        
        if form.is_valid():
        
            data = form.cleaned_data;
            #Опытным путем выяснено, что при длине параметра, равной 11 символам, odbc-драйвер
            #сегфолтится. Поэтому юзаем костыль, обрезая строку до первых 10 символов.
            #TODO: зарепортить багу, починить.
            results = Citizen.objects.filter(famil__startswith=data['last_name'][:10].strip())
            
            if data['first_name']:
                results = results.filter(imja__startswith=data['first_name'][:10].strip())
            if data['patronymic']:
                results = results.filter(otch__startswith=data['patronymic'][:10].strip())
            

            if request.is_ajax():
                return render_by_request_context(request, 'okno/search_results.html', { 'form': form, 
                                                                                       'data': results })
            else:
                return render_by_request_context(request, 'okno/search.html', {'form': form, 'data': results })
    else:
        form = SearchForm()
        
    if request.is_ajax():
        return render_by_request_context(request, 'okno/search_results.html')
    
    return render_by_request_context(request, 'okno/search.html', {'form': form })

@login_required
def statistics(request, year=None, month=None, day=None):
    
    from django.db.models import Count
    
    try:
        _date = datetime.date(int(year), int(month), int(day))
    # TypeError - дата не указана
    # ValueError - дала не верна
    except Exception:
        _date = datetime.date.today()
    
    day_stats = Statement.objects.filter(date=_date)
    
    total_for_day = day_stats.count()

    max_day_number = calendar.monthrange(_date.year, _date.month)[1]
    month_stats = Statement.objects.filter(
        date__gte=datetime.date(_date.year, _date.month, 1)).filter(
        date__lte=datetime.date(_date.year, _date.month, max_day_number))
    
    total_for_month = month_stats.count()
      
    total_for_day_by_user = [{ 'user': User.objects.get(id=x['user']), 'total': x['total']} for x in day_stats.values('user').annotate(total=Count('user'))]
    total_for_month_by_user = [{ 'user': User.objects.get(id=x['user']), 'total': x['total']} for x in month_stats.values('user').annotate(total=Count('user'))]
    #TODO: локализовать название месяца
    data = {'date': _date, 'month_name': _date.strftime('%B'),
                 'day': {
                        'total': total_for_day,
                        'verbose': total_for_day_by_user,
                },
                 'month': {
                        'total': total_for_month,
                        'verbose': total_for_month_by_user,
                }}
    
    return render_by_request_context(request, 'okno/statistics.html', {'data': data })